package cz.schovjan.proj.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import cz.schovjan.proj.dao.IBandDao;
import cz.schovjan.proj.dao.IMemberDao;
import cz.schovjan.proj.dto.Member;
import cz.schovjan.proj.entity.BandEntity;
import cz.schovjan.proj.entity.MemberEntity;
import cz.schovjan.proj.service.IMember;

/**
 * Implementace rozhrani IMember pro praci se clenama kapel.
 * @author schovjan
 *
 */
@Transactional
public class MemberImpl implements IMember {

	@Autowired
	private IMemberDao memberDao;
	
	@Autowired
	private IBandDao bandDao;
	
	
	@Override
	public void add(String nick, String name, String surname, String email, String phone, Date dateOfBirth, String job) {
		MemberEntity me = new MemberEntity();
		me.setNick(nick);
		me.setName(name);
		me.setSurname(surname);
		me.setEmail(email);
		me.setPhone(phone);
		me.setDateOfBirth(dateOfBirth);
		me.setJob(job);
		
		memberDao.add(me);
	}


	@Override
	public List<Member> findAll() {
		List<Member> result = new ArrayList<Member>();
		List<MemberEntity> memberEntitys = memberDao.findAll();
		
		for (MemberEntity me : memberEntitys) {
			result.add(loadMember(me));
		}
		
		return result;
	}


	@Override
	public Member find(int id) {
		MemberEntity me = memberDao.find(id);

		return loadMember(me);
	}
	
	/**
	 * Vrati nasetovaneho clena.
	 * @param me
	 * @return
	 */
	private Member loadMember(MemberEntity me) {
		
		if (me==null) {
			return null;
		}
		
		Member m = new Member();
		m.setId(me.getId());
		m.setNick(me.getNick());
		m.setName(me.getName());
		m.setSurname(me.getSurname());
		m.setEmail(me.getEmail());
		m.setPhone(me.getPhone());
		m.setDateOfBirth(me.getDateOfBirth());
		m.setJob(me.getJob());
		
		return m;
	}


	@Override
	public void delete(int id) {
		memberDao.delete(id);
	}
	
	
	@Override
	public void save(Integer id, String nick, String name, String surname, String email, String phone, Date dateOfBirth, String job) {
		MemberEntity me = memberDao.find(id);
		me.setNick(nick);
		me.setName(name);
		me.setSurname(surname);
		me.setEmail(email);
		me.setPhone(phone);
		me.setDateOfBirth(dateOfBirth);
		me.setJob(job);
	}

	
	@Override
	public List<Member> findOtherMembers(int id) {
		List<Member> result = new ArrayList<Member>();
		List<MemberEntity> meAll = memberDao.findAll();
		BandEntity band = bandDao.find(id);
		
		for (MemberEntity me : band.getMembers()) {
			meAll.remove(me);
		}
		for (MemberEntity me : meAll) {
			result.add(loadMember(me));
		}
		
		return result;
	}
	
}
